package com.chuantou.yuba.ui;

import java.util.HashMap;
import java.util.regex.Matcher;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.smssdk.SMSSDK;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;

public class FindPasswordActivity extends BaseActionBarActivity implements OnClickListener {
	private static final int WHAT_REMOVE_ERROR_MSG = 1;
	private static final int WHAT_COUNT_DOWN = 2;
	private EditText mPhoneView;
	private EditText mVerifyCodeView;
	private TextView mCountDownView;
	private Button mSubmitButton;
	private ProgressDialog mFindDialog;
	private TextView mErrorView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_password);
		setTitle(R.string.find_password);
		setupViews();
	}

	private void setupViews() {
		mPhoneView = (EditText) findViewById(R.id.phone);
		mVerifyCodeView = (EditText) findViewById(R.id.verify_code);
		mErrorView = (TextView) findViewById(R.id.message);
		mCountDownView = (TextView) findViewById(R.id.count_down);
		mCountDownView.setOnClickListener(this);
		invalidateSendVerifyCodeTextView();
		mSubmitButton = (Button) findViewById(R.id.submit);
		mSubmitButton.setOnClickListener(this);
	}

	private void invalidateSendVerifyCodeTextView() {
		long time = Constants.sLastSendVerifyCodeTime;
		long diff = System.currentTimeMillis() - time;
		if (diff > 60 * 1000) {
			mCountDownView.setEnabled(true);
			mCountDownView.setText(R.string.get_verify_code);
		} else {
			int second = 60 - (int) (diff / 1000);
			mCountDownView.setText(getString(R.string.get_verify_code_after, second));
			mCountDownView.setEnabled(false);
			mHandler.sendEmptyMessageDelayed(WHAT_COUNT_DOWN, 1000);
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WHAT_REMOVE_ERROR_MSG:
				if (!hasDestroyed()) {
					mErrorView.setVisibility(View.GONE);
				}
				break;
			case WHAT_COUNT_DOWN:
				if (!hasDestroyed()) {
					invalidateSendVerifyCodeTextView();
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.submit:
			findPassword();
			break;
		case R.id.count_down:
			checkPhoneUnique();
			break;
		default:
			break;
		}
	}

	private void showErrorMessage(String msg) {
		mHandler.removeMessages(WHAT_REMOVE_ERROR_MSG);
		mErrorView.setVisibility(View.VISIBLE);
		mErrorView.setText(msg);
		mHandler.sendEmptyMessageDelayed(WHAT_REMOVE_ERROR_MSG, 1500);
	}

	private void findPassword() {
		if (UiUtil.isFastDoubleClick())
			return;
		final String phone = mPhoneView.getText().toString().trim();
		if (TextUtils.isEmpty(phone) || phone.length() != 11) {
			showErrorMessage(getString(R.string.input_phone_error));
			return;
		} else {
			Matcher matcher = Constants.PHONE_PATTERN.matcher(phone);
			if (!matcher.matches()) {
				showErrorMessage(getString(R.string.input_phone_error));
				return;
			}
		}

		final String verifyCode = mVerifyCodeView.getText().toString().trim();
		if (TextUtils.isEmpty(verifyCode)) {
			showErrorMessage(getString(R.string.input_verify_code_error));
			return;
		}
		showFindDialog();
		String url = UriHelper.getVerifySmsCodeUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_MOBILE, phone);
		params.put(UriHelper.PARAMS_CODE, verifyCode);
		GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

			@Override
			public void onResponse(BaseTO response) {
				if (!hasDestroyed()) {
					dismissFindDialog();
					if (response == null) {
						showErrorMessage(getString(R.string.server_error));
					} else {
						if (response.isSuccess()) {
							Intent intent = new Intent(FindPasswordActivity.this, ResetPasswordActivity.class);
							intent.putExtra(Constants.EXTRA_PHONE, phone);
							startActivity(intent);
							finish();
						} else {
							String msg = response.getMsg();
							msg = TextUtils.isEmpty(msg) ? getString(R.string.find_password_error) : msg;
							showErrorMessage(msg);
						}
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					dismissFindDialog();
					showErrorMessage(getString(R.string.request_error));
				}
			}
		}, params, BaseTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	private void showFindDialog() {
		if (mFindDialog != null && mFindDialog.isShowing()) {
			return;
		}
		mFindDialog = new ProgressDialog(this);
		mFindDialog.setCancelable(false);
		mFindDialog.setMessage(getString(R.string.submiting));
		mFindDialog.show();
	}

	private void dismissFindDialog() {
		if (mFindDialog != null && mFindDialog.isShowing()) {
			mFindDialog.dismiss();
		}
	}

	/***
	 * 检查手机号码唯一性
	 */
	private void checkPhoneUnique() {
		final String phone = mPhoneView.getText().toString().trim();
		if (TextUtils.isEmpty(phone) || phone.length() != 11) {
			showErrorMessage(getString(R.string.input_phone_error));
			return;
		} else {
			Matcher matcher = Constants.PHONE_PATTERN.matcher(phone);
			if (!matcher.matches()) {
				showErrorMessage(getString(R.string.input_phone_error));
				return;
			}
		}
		showFindDialog();
		String url = UriHelper.getCheckPhoneUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_MOBILE, phone);
		GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

			@Override
			public void onResponse(BaseTO response) {
				if (!hasDestroyed()) {
					dismissFindDialog();
					if (response == null) {
						sendVerifyCode(phone);
					} else {
						if (response.isSuccess()) {
							showErrorMessage(getString(R.string.phone_is_not_registed));
						} else {
							sendVerifyCode(phone);
						}
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					dismissFindDialog();
					showErrorMessage(getString(R.string.request_error));
				}
			}
		}, params, BaseTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	private void sendVerifyCode(String phone) {
		SMSSDK.initSDK(getApplicationContext(), Constants.MOB_APP_KEY, Constants.MOB_APP_SECRET);
		String[] country = SMSSDK.getCountry(Constants.DEFAULT_COUNTRY_ID);
		String code = country[1];
		SMSSDK.getVerificationCode(code, phone);
		Constants.sLastSendVerifyCodeTime = System.currentTimeMillis();
		invalidateSendVerifyCodeTextView();
	}
}
